package com.hsd.netty.server.strategy;

import com.hsd.netty.server.common.NettyMessage;
import com.hsd.netty.server.enums.MessageType;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author s.he
 * on 2020/6/1
 */
@Component
public class MessageHandlerAdapter {
    public static Map<MessageType, MessageTypeHandler> handlerMap = new HashMap<>();

    static  {
        handlerMap.put(MessageType.LOGIN, new LoginMessageHandler());
        handlerMap.put(MessageType.HEART_BEAT, new HeartBeatMessageHandler());
        handlerMap.put(MessageType.REQUEST, new RequestMessageHandler());
    }

    public NettyMessage handler(byte type, ChannelHandlerContext channelHandlerContext, NettyMessage nettyMessage) {
        MessageType messageType = MessageType.getMessageType(type);
        /**
         * 不是登录请求，登录拦截
         */
        if(!MessageType.LOGIN.equals(messageType)) {
            NettyMessage loginFilter = handlerMap.get(messageType).loginFilter(channelHandlerContext, nettyMessage);
            if(loginFilter.getNettyHeader() != null) {
                return loginFilter;
            }
        }
        /**
         * 如果是业务请求，则只做鉴权拦截
         */
        if(MessageType.REQUEST.equals(messageType)) {
            return new NettyMessage();
        }
        return handlerMap.get(messageType).handler(channelHandlerContext, nettyMessage);
    }

}
